const { cartFormatError, invalidGoodsID } = require("../constant/err.type");
const { getGoodsInfo } = require("../service/goods.service");

const validator = (rules) => {
  return async (ctx, next) => {
    try {
      ctx.verifyParams(rules);
    } catch (err) {
      console.error(err);
      cartFormatError.result = err;
      return ctx.app.emit("error", cartFormatError, ctx);
    }

    await next();
  };
};

const verifyGoods = async (ctx, next) => {
  const { goods_id } = ctx.request.body;
  // 合理性 deferent
  try {
    const res = await getGoodsInfo({ id: goods_id });

    if (!res) {
      console.error("无效的商品id", { goods_id });
      ctx.app.emit("error", invalidGoodsID, ctx);
      return;
    }
  } catch (err) {
    console.error("无效的商品id", err);
    ctx.app.emit("error", invalidGoodsID, ctx);
    return;
  }

  await next();
};

module.exports = {
  validator,
  verifyGoods,
};
